package com.lxq.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;

import com.lxq.common.DbHelper;
import com.lxq.dao.CardDao;
import com.lxq.dao.impl.common.BaseDaoImpl;
import com.lxq.entity.Card;

public class CardDaoImpl extends BaseDaoImpl<Card> implements CardDao {

	@Override
	public Card findByCardNumber(String cardNumber) {
		Card card = null;

		Connection conn = null;
		String sql = "select * from " + getTableName() + " where cardNumber = ?";
		try {

			conn = DbHelper.getConn();
			card = qr.query(conn, sql, beanHandler, cardNumber);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				DbHelper.close(conn);
			}
		}

		return card;
	}

	@Override
	public boolean updateCurrentBalance(String cardNumber, String updateBalance) {

		if (findByCardNumber(cardNumber) == null) {
			return false;
		}

		Connection conn = null;

		String sql = "update " + getTableName() + " set currentBalance=? where cardNumber=?";
		try {

			conn = DbHelper.getConn();
			qr.update(conn , sql, updateBalance, cardNumber);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				DbHelper.close(conn);
			}
		}
		return true;
	}

	@Override
	public boolean updateCardState(String cardNumber, int newState) {
		if (findByCardNumber(cardNumber) == null) {
			return false;
		}

		Connection conn = null;
		
		String sql = "update " + getTableName() + " set cardState=? where cardNumber=?";
		try {

			conn = DbHelper.getConn();
			qr.update(conn, sql, newState, cardNumber);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				DbHelper.close(conn);
			}
		}
		return true;
	}

}
